﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SQLHelper;
using System.Data.SqlClient;

namespace BBS
{
    public partial class ThemeDetailPage : BasePage
    {
        protected string themeContent;
        protected string themeMasterId;
        protected void Page_Load (object sender, EventArgs e)
        {
            this.themeContent = (string)Session["themeContent"];
            this.themeMasterId = (string)Session["themeMasterId"];
            if ( !IsPostBack )
            {
                this.LoadTheme();
                this.InitThisReplyModel();
            }
            this.LoadThemeReplys();
        }

        /// <summary>
        /// 加载帖子内容
        /// </summary>
        private void LoadTheme ()
        {
            string themeId = Request.QueryString["themeId"].ToString();
            string getThemeSqlStr = string.Format("SELECT TITLE,CONTENT,PUBLISH_DATE,PICKNAME,THEME.ACCOUNT_ID FROM ACCOUNT,THEME WHERE THEME_ID={0} AND ACCOUNT.ACCOUNT_ID=THEME.ACCOUNT_ID", themeId);
            SQLHelperSingleton.TryQueryByDataReader(getThemeSqlStr, this.SetThemeContent, this.Fail);
        }

        /// <summary>
        /// 加载帖子的评论s
        /// </summary>
        private void LoadThemeReplys ()
        {
            string themeId = Request.QueryString["themeId"].ToString();
            string getReplyStr = string.Format("SELECT REPLY.REPLY_CONTENT AS 回复内容,REPLY.REPLY_DATE AS 回复日期,REPLY_ACCOUNT.PICKNAME AS 回复人昵称,TARGET_ACCOUNT.PICKNAME AS 被回复人昵称,REPLY_ACCOUNT.ACCOUNT_ID AS 回复人ID,TARGET_ACCOUNT.ACCOUNT_ID AS 被回复人ID,REPLY.REPLY_ID AS 回复ID,REPLY.TARGET_REPLY_ID AS 被回复ID FROM REPLY,ACCOUNT AS REPLY_ACCOUNT,ACCOUNT AS TARGET_ACCOUNT WHERE REPLY.THEME_ID = {0} AND REPLY.REPLY_ACCOUNT_ID = REPLY_ACCOUNT.ACCOUNT_ID AND REPLY.TARGET_ACCOUNT_ID = TARGET_ACCOUNT.ACCOUNT_ID ORDER BY REPLY.REPLY_DATE;", themeId);
            SQLHelperSingleton.TryQueryByDataReader(getReplyStr, this.AddReplyViews, this.Fail);
        }

        /// <summary>
        /// 初始化一个评论model，将用户评论的信息存放到Session中
        /// </summary>
        private void InitThisReplyModel ()
        {
            Dictionary<string, string> model = new Dictionary<string, string>();

            string themeId = Request.QueryString["themeId"].ToString();

            model.Remove("themeId");
            model.Add("themeId", themeId);
            model.Add("targetAccountId", this.themeMasterId);
            User user = (User)Session["user"];
            if ( user != null )
            {
                model.Add("replyAccountId", user.UserId);
            }

            Session["replyModel"] = model;
        }

        /// <summary>
        /// 取得帖子的内容
        /// </summary>
        /// <param name="reader"></param>
        private void SetThemeContent (SqlDataReader reader)
        {
            if ( reader.Read() )
            {
                this.themeContent = reader["CONTENT"].ToString();
                this.lblTitle.Text = reader["TITLE"].ToString();
                this.lblPublishDate.Text = reader["PUBLISH_DATE"].ToString();
                this.lblAccount.Text = reader["PICKNAME"].ToString();
                this.themeMasterId = reader["ACCOUNT_ID"].ToString();

                //回发的时候this.themeContent会被重置，所以用Session来保存
                Session["themeContent"] = this.themeContent;
                Session["themeMasterId"] = this.themeMasterId;
            }
        }

        /// <summary>
        /// 回复楼主
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lbReplyMaster_Click (object sender, EventArgs e)
        {
            User user = (User)Session["user"];
            if ( user == null )
            {
                this.ExecuteJS("alert('请先登陆！');window.location.href='Login.aspx';");
                return;
            }

            Dictionary<string, string> replyDic = (Dictionary<string, string>)Session["replyModel"];
            replyDic.Remove("replyAccountId");
            replyDic.Add("replyAccountId", user.UserId);
            Session["replyModel"] = replyDic;

            this.lblReplyInfo.Text = "";
            this.lblReplyInfo.Height = 0;

            this.txtReplyContent.Focus();
        }

        /// <summary>
        /// 提交回复
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnReply_Click (object sender, EventArgs e)
        {
            User user = (User)Session["user"];
            if ( user == null )
            {
                this.ExecuteJS("alert('请先登陆！');window.location.href='Login.aspx';");
                return;
            }

            if ( this.txtReplyContent.Text == "" )
            {
                this.Alert("回复内容不能为空！");
                return;
            }

            Dictionary<string, string> replyDic = (Dictionary<string, string>)Session["replyModel"];
            string replyDate = DateTime.Now.ToString();
            string targetReplyId = "";
            if ( replyDic.TryGetValue("targetReplyId", out targetReplyId) == false )
            {
                targetReplyId = "NULL";
            } else if ( targetReplyId == "" )
            {
                targetReplyId = "NULL";
            }

            string insertReplyStr = string.Format("INSERT INTO REPLY(THEME_ID,REPLY_ACCOUNT_ID,TARGET_ACCOUNT_ID,REPLY_DATE,REPLY_CONTENT,TARGET_REPLY_ID) VALUES({0},{1},{2},'{3}','{4}',{5})", replyDic["themeId"], replyDic["replyAccountId"], replyDic["targetAccountId"], replyDate, this.txtReplyContent.Text.Replace("\r\n", "<br />"), targetReplyId);
            SQLHelperSingleton.TryExecuteNonQuery(insertReplyStr, this.Fail);

            this.txtReplyContent.Text = "";
            this.RedirectTo("ThemeDetailPage.aspx?themeId=" + replyDic["themeId"]);
        }

        /// <summary>
        /// 取得所有回复，并动态加载评论视图
        /// </summary>
        /// <param name="reader"></param>
        private void AddReplyViews (SqlDataReader reader)
        {
            this.panReply.Controls.Clear();
            for ( int floor = 1; reader.Read(); floor++ )
            {
                int themeId = int.Parse(Request.QueryString["themeId"].ToString());
                string replyContent = reader["回复内容"].ToString();
                string replyDate = reader["回复日期"].ToString();
                string replyAccountPickName = reader["回复人昵称"].ToString();
                string targetAccountPickName = reader["被回复人昵称"].ToString();
                int replyAccountId = int.Parse(reader["回复人ID"].ToString());
                int targetAccountId = int.Parse(reader["被回复人ID"].ToString());
                int replyId = int.Parse(reader["回复ID"].ToString());
                int targetReplyId = -1;
                if ( reader["被回复ID"] != null && reader["被回复ID"].ToString() != "" )
                {
                    string re = reader["被回复ID"].ToString();
                    targetReplyId = int.Parse(reader["被回复ID"].ToString());
                }

                ReplyModel replyModel = new ReplyModel(themeId, replyId, targetReplyId, replyAccountId, targetAccountId, replyAccountPickName, targetAccountPickName, replyDate, replyContent);

                ReplyView replyView = (ReplyView)Page.LoadControl("ReplyView.ascx");
                replyView.replyModel = replyModel;
                replyView.ReplyDel = this.ReplyViewButtonClick;
                replyView.Floor = floor;
                replyView.Attributes.Add("Width", "100%");
                this.panReply.Controls.Add(replyView);
            }
        }

        private void ReplyViewButtonClick (ReplyView replyView)
        {
            User user = (User)Session["user"];
            if ( user == null )
            {
                this.ExecuteJS("alert('请先登陆！');window.location.href='Login.aspx';");
                return;
            }

            Dictionary<string, string> replyDic = (Dictionary<string, string>)Session["replyModel"];

            replyDic.Remove("replyAccountId");
            replyDic.Remove("targetAccountId");
            replyDic.Remove("targetReplyId");

            replyDic.Add("replyAccountId", user.UserId);
            replyDic.Add("targetAccountId", replyView.replyModel.ReplyAccountId.ToString());
            replyDic.Add("targetReplyId", replyView.replyModel.ReplyId.ToString());
            Session["replyModel"] = replyDic;

            this.lblReplyInfo.Height = 20;
            this.lblReplyInfo.Text = string.Format("回复第 {0} 楼：", replyView.Floor);

            this.txtReplyContent.Focus();
        }

        private void Fail (string err)
        {
            this.Alert(err);
        }
    }
}